﻿using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;
using Unread.Business.Data.Syndication;
using Unread.Business.Models;
using Unread.Business.Repositories.Interfaces;
using Windows.Web.Syndication;

namespace Unread.Business.Repositories
{
    [Export(typeof(IFeedItemRepository))]
    internal class FeedItemRepository : IFeedItemRepository
    {
        private readonly ISyndicationClient _syndicationClient;

        [ImportingConstructor]
        public FeedItemRepository(ISyndicationClient syndicationClient)
        {
            if (syndicationClient == null) throw new ArgumentNullException("syndicationClient");

            _syndicationClient = syndicationClient;
        }

        public async Task<IEnumerable<FeedItem>> GetAll(Uri syndicationUri)
        {
            if (syndicationUri == null) throw new ArgumentNullException("syndicationUri");

            var syndicationFeed = await _syndicationClient.RetrieveFeedAsync(syndicationUri);

            return (from item in syndicationFeed.Items
                    select new FeedItem
                    {
                        Id = Guid.NewGuid(),
                        Title = item.Title.GetText(),
                        Summary = item.Summary.GetText(),
                        Link = (item.Links.Any() ? item.Links.First().Uri : null),
                        PublishDate = item.PublishedDate.LocalDateTime,
                        Image = syndicationFeed.ImageUri
                    }).ToList();
        }
    }
}